package com.example.demo.array;

import java.util.HashMap;

/**
 * 和为 K 的子数组
 * https://leetcode.cn/problems/QTMn0o/description/
 */
public class SubarraySum {

    public int subarraySum(int[] nums, int k) {
        int count = 0;
        for (int i = 0; i < nums.length; i++) {
            int sum = 0;
            for (int j = i; j >= 0; j--) {
                sum += nums[j];
                if (sum == k) {
                    count++;
                }
            }
        }
        return count;
    }

    public int subarraySum2(int[] nums, int k) {
        int count = 0, pre = 0;

        HashMap<Integer, Integer> mp = new HashMap<>();
        mp.put(0, 1);

        for (int num : nums) {
            pre += num;
            if (mp.containsKey(pre - k)) {
                count += mp.get(pre - k);
            }
            mp.put(pre, mp.getOrDefault(pre, 0) + 1);
        }

        return count;
    }
}
